#pragma once

#include <iostream>
#include <vector>
#include <string>
#include <poll.h>
#include "Socket.hpp"

static const uint16_t defaultport = 8080;
static const int fd_num_max = 64;
int defaultfd = -1;
int nonevent = 0;

class PollServer
{
public:
    PollServer(const uint16_t port = defaultport) : _port(port)
    {
        for(int i = 0; i < fd_num_max; ++i)
        {
            _event_fds[i].fd = defaultfd;
            _event_fds[i].events = nonevent;
            _event_fds[i].revents = nonevent;
        }
    }

    bool Init()
    {
        _listensock.Socket();
        _listensock.Bind(_port);
        _listensock.Listen();
        lg(Info, "server init.");
        return true;
    }

    void Start()
    {
        _event_fds[0].fd = _listensock.Fd();
        _event_fds[0].events = POLL_IN;
        int timeout = 3000;
        for (;;)
        {
            int n = poll(_event_fds, fd_num_max, timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out..." << std::endl;
                break;
            case -1:
                std::cout << "poll err." << endl;
                break;
            default:
                std::cout << "a fd is selected." << std::endl;
                Dispatcher();
                break;
            }
        }
    }

    ~PollServer()
    {
        _listensock.Close();
    }

private:

    void Accepter()
    {
        // 连接事件就绪了
        std::string clientip;
        uint16_t clientport;
        int sock = _listensock.Accept(&clientip, &clientport);
        if (sock < 0)
            return;
        lg(Info, "accept success , [%s]:%d", clientip.c_str(), clientport);

        int pos = 1;
        while (pos < fd_num_max)
        {
            if (_event_fds[pos].fd == defaultfd)
                break;
            ++pos;
        }

        if (pos == fd_num_max)
        {
            lg(Warning, "fd_array is full! close fd %d now.", sock);
            close(sock);
        }
        else
        {
            // 将收到的链接对应的文件描述符放入找到的第一个空位置
            _event_fds[pos].fd = sock;
            _event_fds[pos].events = POLL_IN;
            _event_fds[pos].revents = nonevent;
        }
    }

    void Recver(int fd, int pos)
    {
        char buffer[1024];
        int n = read(fd, buffer, sizeof(buffer)-1);
        if(n > 0)
        {
            buffer[n-1] = 0;
            cout << "get a message:" << buffer << endl;
        }
        else if(n == 0)
        {
            lg(Info, "client closed. me too, the fd is: %d", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd;
        }
        else
        {
            lg(Warning, "recv error! the fd is: %d", fd);
            close(fd);
            _event_fds[pos].fd = defaultfd;
        }
    }

    void Dispatcher()
    {
        for (int i = 0; i < fd_num_max; ++i)
        {
            auto& efd = _event_fds[i];
            int fd = efd.fd;
            if (fd == defaultfd)
                continue;

            if (efd.revents & POLL_IN)
            {
                if (fd == _listensock.Fd())
                {
                    lg(Info, "accepter received.");
                    Accepter();
                }
                else
                {
                    lg(Info, "recver received.");
                    Recver(fd, i);
                }
            }
        }
    }

private:
    // int fd_array[fd_num_max];
    struct pollfd _event_fds[fd_num_max];
    Sock _listensock;
    uint16_t _port;
};